import { SysLogininfor } from '@common/domain/sys_logininfor';
import { db } from '../database/db';

export async function getLogininforList(offset: number|string = 0, limit: number|string = 10, query?: any) {
    // 基础查询
    let baseQuery = db.selectFrom('sys_logininfor');

    // 添加查询条件
    if (query?.user_name) {
        baseQuery = baseQuery.where('user_name', 'like', `%${query.user_name}%`);
    }
    if (query?.ipaddr) {
        baseQuery = baseQuery.where('ipaddr', 'like', `%${query.ipaddr}%`);
    }
    if (query?.status !== undefined && query?.status !== '') {
        baseQuery = baseQuery.where('status', '=', query.status);
    }
    if (query?.login_time_start) {
        baseQuery = baseQuery.where('login_time', '>=', new Date(query.login_time_start));
    }
    if (query?.login_time_end) {
        baseQuery = baseQuery.where('login_time', '<=', new Date(query.login_time_end));
    }

    // 查询总数
    const [{ count }] = await baseQuery
        .select(db.fn.countAll().as('count'))
        .execute();
    const total = Number(count);

    if (total === 0) {
        return { list: [], total: 0 };
    }

    // 查询列表
    const list = await baseQuery
        .selectAll()
        .orderBy('login_time', 'desc')
        .offset(Number(offset))
        .limit(Number(limit))
        .execute();

    return { list, total };
}

export async function getLogininforById(info_id: number) {
    return await db.selectFrom('sys_logininfor')
        .selectAll()
        .where('info_id', '=', info_id)
        .executeTakeFirst();
}

export const createLogininfor = async (data: SysLogininfor) => {
    const result = await db.insertInto('sys_logininfor').values([data]).executeTakeFirst();
    return result.insertId;
}

export async function deleteLogininfor(info_id: number) {
    const result = await db.deleteFrom('sys_logininfor')
        .where('info_id', '=', info_id)
        .executeTakeFirst();
    return result.numDeletedRows;
}

export async function cleanLogininfor() {
    const result = await db.deleteFrom('sys_logininfor').executeTakeFirst();
    return result.numDeletedRows;
} 